package com.googlecode.strutson

import com.googlecode.strutson.commands.CreateApp
import com.googlecode.strutson.commands.CreateModel
import com.googlecode.strutson.commands.Generate
import com.googlecode.strutson.commands.RunApp
import java.security.CodeSource
import java.security.ProtectionDomain
import com.googlecode.strutson.utils.EnvVariables

class Main {
    static void main(args) {

        //get strutson_home
        ProtectionDomain protectionDomain = Main.class.protectionDomain
        CodeSource codeSource = protectionDomain.codeSource
        URL loc = codeSource.getLocation();
        File file = new File(loc.toURI())
        EnvVariables.HOME = file.parentFile.absolutePath

        //parse cli
        CliBuilder cli = new CliBuilder()

        cli.h(longOpt: 'help', 'Usage information');
        cli.c(longOpt: 'create-app', 'Create a new web app');
        cli.m(longOpt: 'create-model', 'Create model class');
        cli.g(longOpt: 'generate', 'Generate views, services and controller from a model class');
        cli.s(longOpt: 'start-app', 'Start current web app');
        cli.r(longOpt: 'rest', 'Generate application and controllers that use the REST plugin');
        cli.f(longOpt: 'force', 'Overwrite generated artifacts');

        def opt = cli.parse(args)
        if (!opt) return;
        if (opt.h) cli.usage()

        if (opt.c) {
            def createApp = new CreateApp()
            createApp.rest = opt.r
            createApp.run()
        } else if (opt.s && EnvVariables.load()) {
            def runApp = new RunApp()
            runApp.run()
        } else if (opt.m && EnvVariables.load()) {
            def createModel = new CreateModel()
            createModel.run()
        } else if (opt.g && EnvVariables.load()) {
            def generate = new Generate()
            generate.overwrite = opt.f
            generate.rest = opt.r
            generate.run()
        } else {
            cli.usage()
        }
    }
}